package com.mycompany.chatapp;

import com.mycompany.chatapp.Databaseacces.ImpDBAction;
import com.mycompany.chatapp.Databaseacces.ImpDBActionResult;
import com.mycompany.chatapp.Databaseacces.Photo;
import com.mycompany.chatapp.Databaseacces.User;
import com.mycompany.screens.ShowContact;
import com.mycompany.screens.ShowThumbnails;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.media.jai.RenderedOp;
import javax.swing.ImageIcon;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.jivesoftware.smack.XMPPException;

/**
 * This class implement de Listener of each peer
 * @author Group C
 */
public class ImpListener implements Listener, PacketListener
{
    String search =null;  
    boolean find=false;
    String answer= null;
    //Define the Logger for ImpListener 
    private final static Logger log = Logger.getLogger(ImpListener.class);
    private String messageFrom=null;
    ImpInstantMessage instantMessage=null;
    private com.mycompany.chatapp.Databaseacces.ImpDBManager dbmanager = null;
    int contactFound=0;
    List<Photo> listFinal=new ArrayList<Photo>();
     List<Object> listFinalUser=new ArrayList<Object>();
    
    List <Photo> photoResultList=new ArrayList <Photo>();
    List <Object> contactResultList=new ArrayList <Object>();
    List<Object> list=new ArrayList <Object>();
    
 public ImpListener(ImpInstantMessage instantMessage) {
    this.instantMessage = instantMessage;  
    flag=false;
 }

    public void processPacket(Packet packet)
    {
        //Basic Configuration for log4j
        BasicConfigurator.configure();

        if (packet instanceof Message) 
        {    
            Message msg = (Message) packet;

            if( (GenericMessage) msg.getProperty("Type") instanceof SearchProfile)
            {
                this.searchProfile(msg);
            }     
            else if( (GenericMessage) msg.getProperty("Type") instanceof SearchResult)
            {
                this.searchResult(msg); 
            }
            else if((GenericMessage) msg.getProperty("Type") instanceof UserContent)
            {
                try {
                    
                    this.userContent(msg);
                    
                } catch (XMPPException ex) {
                    java.util.logging.Logger.getLogger(ImpListener.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    /**
     * This method analyze the content of SearchProfile message in the Listener
     * @param msg 
     */
    public void searchProfile (Message msg)
    {  
        if (log.isDebugEnabled()) {
            log.info("SearchProfile received");
        }
        ImpSearchProfile content = (ImpSearchProfile) msg.getProperty("Type");
        int typeOfQuery = content.getType();
        search = content.getContent();
        boolean found=false;
        ImpDBActionResult result=null;
        int size=0;
        ImpDBAction action =null;
        
        switch (typeOfQuery){
            //case of 1st type of query (tag)
            case 1:
                if (log.isDebugEnabled()) {
                    log.info("Type of Query"+typeOfQuery);
                }
                dbmanager = com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                action.setActionId("consulta.imagen.libre");
                action.setParameters(new String[]{search});
                result = dbmanager.execute(action);
                size= result.getResult().size();
                if (size==0)
                {
                    if (log.isDebugEnabled()) {
                       log.info(instantMessage.getXMPPConnection().getUser() +"No results");
                    }
                    found =false;
                }
                else
                {
                    found=true;
                    if (log.isDebugEnabled()) {
                       log.info(instantMessage.getXMPPConnection().getUser() +"There are results, we are introducing thumbnails");
                    }
                    //creacio del thumbnail***********
                    list=result.getResult();
                    
                    Photo picture=new Photo();
                    if (log.isDebugEnabled()) {
                       log.info("Thumbnail introduced");
                    }
                }
          
                
                break;
           
            //case of 2nd type of query (taxonomy)
            case 2:
                
                dbmanager=  com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                String word1="";
                String word2="";
                String delimiter="\\ ";
                String[] tupla=search.split(delimiter);
                word1=tupla[0];
                word2=tupla[1];
                log.info("word1 "+word1+" word2 "+word2);
                action.setActionId("consulta.imagen.ontologia");
                action.setParameters(new String[]{word2,word1});
                //action.setParameters(tupla);
                result = dbmanager.execute(action);
                size= result.getResult().size();
                if (size==0){
                    found =false;
                }
                else{
                    //creacio del thumbnail***********
                    found =true;
                     list=result.getResult();
                }
                
                break;
            
            //case of the 3rd type of query (Article option 1)
            case 3:
               
                dbmanager=  com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                action.setActionId("consulta.imagen.noticiaentera");
                action.setParameters(new String[]{search});
                result = dbmanager.execute(action);
                size= result.getResult().size();
                if (size==0){
                    found =false;
                }
                else{
                    //do something with the article
                    found =true;
                    list=result.getResult();
                }
                
                break;
            
            //case of the 4th type of query (Article option 2)
            case 4: 
                
                dbmanager=  com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                action.setActionId("consulta.imagen.noticiatitulo");
                action.setParameters(new String[]{search});
                result = dbmanager.execute(action);
                size= result.getResult().size();
                if (size==0){
                    found =false;
                }
                else{
                    //do something with the article
                    found =true;
                     list=result.getResult();
                }
                
                break;
            
            //case of the 5th type of query (Article option 3)
            case 5: 
                
                dbmanager=  com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                action.setActionId("consulta.imagen.noticiacontiguos");
                action.setParameters(new String[]{search});
                result = dbmanager.execute(action);
                size= result.getResult().size();
                if (size==0){
                    found =false;
                }
                else{
                    //do something with the article
                    found =true;
                     list=result.getResult();
                }
                
                break;
            
            //case of the 6th type of query (Contact)
            case 6: 
                String consulta =null;
                dbmanager=  com.mycompany.chatapp.Databaseacces.ImpDBManager.getInstanceManager();
                action = new ImpDBAction();
                if(search.contains("@"))
                    consulta="consulta.autor.mail";
                else
                    consulta="consulta.autor.nickname";
                action.setActionId(consulta);
                action.setParameters(new String[]{search});
                result = dbmanager.execute(action);
                
                log.info("imprimimos result :"+search);
                size= result.getResult().size();
                if (size==0){
                    found =false;
                }
                else{
                    found =true;
                    listFinalUser=result.getResult();
                    
                }    
                
                break;
            
            default:
                if (log.isDebugEnabled()) {
                    log.info("Type of search not available! ");
                }
                
                break;
        }
        find =  instantMessage.searchContent(search);  

        if(found)
        {     
            if (log.isDebugEnabled()) {
                log.info("Sending the searchPRofile message"+typeOfQuery);
            }
            if((typeOfQuery==1)|| (typeOfQuery==2) || (typeOfQuery==3) || (typeOfQuery==4)|| (typeOfQuery==5))
            {
                  ImpSearchResult resulted = new ImpSearchResult(list, content.getFrom(),
                        content.getTo());
                instantMessage.sendMessageSearchResult(resulted, content.getTo());
                
            }
            if(typeOfQuery==6)
            {
                 ImpSearchResult resulted = new ImpSearchResult(listFinalUser, content.getFrom(),
                        content.getTo());
                instantMessage.sendMessageSearchResult(resulted, content.getFrom());
            }
                       
        }
        else{
            if (log.isDebugEnabled()) {
                log.info(instantMessage.getXMPPConnection().getUser() +" hasn't found the information");
            }
            
        }
    }
    
    /**
     * This method analyze the content of SearchResult message in the Listener
     * @param msg 
     */
    public void searchResult (Message msg)
    {
        if (log.isDebugEnabled()) {
            log.info("SearchResult received");
        }
        ImpSearchResult content = (ImpSearchResult) msg.getProperty("Type");
        String msgFrom = msg.getFrom();
        int typeOfResult = 0;
        List <Object> searchResultList=content.getContent();
        
        for(Object res : searchResultList){
            if (res instanceof Photo){
                typeOfResult = 1;
                if (log.isDebugEnabled()) {
                    log.info("SearchResult type Photo");
                }
            }
            else if (res instanceof Object){
                if (log.isDebugEnabled()) {
                    log.info("SearchResult type User");
                }
                typeOfResult = 2;
            }
            
            else{
                if (log.isDebugEnabled()) {
                    log.info("The result is not valid");
                }
            }
            break;
        }
        
        if (typeOfResult==1){
            //photoResultList=(List<Photo>)(Photo) searchResultList;
            //Cridar a una funcio dels screens en la que es passa 
            //photoResultList com a parametre
            ShowThumbnails show = new ShowThumbnails(searchResultList,instantMessage, msgFrom);
            show.setVisible(true);
            
        //Show the value of the Searched Content
          
        
            Photo picture=new Photo();
        }
        if (typeOfResult == 2){
            if(flag==false){
                flag=true;
              
                contactResultList=searchResultList;
                showcontact = new ShowContact(contactResultList,instantMessage);
                showcontact.setVisible(true);   
            //Cridar a una funcio dels screens en la que es passa 
            //contactResultList com a parametre
            }
        }
    }
    
    /**
     * This method sends a File to ohter gtalk user
     * @param msg
     * @throws XMPPException 
     */
    public void userContent(Message msg) throws XMPPException
    {
        ImpUserContent content = (ImpUserContent) msg.getProperty("Type");
        
        //get the fileName of the message ImpUserContent
        String fileName=content.getURLContent();
        if(log.isDebugEnabled())
            log.info("I receive the petition of: "+fileName);
        
        //Get the fully userID of the message ImpUserContent
        String addressDest=content.getIDUser();
        if(log.isDebugEnabled())
            log.info("I send the content to: "+addressDest);
        
        //Initiate the fileTransfer
        instantMessage.fileTransfer(fileName, addressDest);
       
    }
    public List<Photo> getPhotoResult(){
        
        return photoResultList;
    }
    public List<Object> getContactResult(){
        return contactResultList;
    }
    public void setFlag(){
        flag=false;
    }
    ShowContact showcontact;
    boolean flag=false;
}    